package com.liit.controller.weixin.controller;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.liit.weixin.auth.utils.AuthUtil;

import com.liit.entity.WeixinUserFormMap;
import com.liit.exception.WeixinException;
import com.liit.mapper.WeixinUserMapper;
import com.liit.util.DictUtils;

@Controller
@RequestMapping(value = "/weixin")
public class WeixinAuthContoller {

	@Resource
	private WeixinUserMapper WeixinUserMapper;

	/**
	 * 用户同意授权后的回调
	 * 
	 * @param code
	 *            用户授权后获取的code
	 * @param state
	 *            重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
	 * @return
	 */
	@RequestMapping(value = "/authorize")
	public String authroize(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "state") Integer state) {
		try {
			// 用户授权url
			Map<String, Object> authResult = AuthUtil.auth_accessToken_url(code);
			WeixinUserFormMap wxUser = WeixinUserMapper.findbyFrist("openid", authResult.get("openid").toString(), WeixinUserFormMap.class);
			if (wxUser == null) {
				throw new NullPointerException("openid not found");
			}
			SecurityUtils.getSubject().getSession().setAttribute("wxUserSession", wxUser);
			return "redirect:" + DictUtils.getDictByValue("WEIXIN_URL", state).getStr("label");
		} catch (Exception e) {
			throw new WeixinException("1001", "授权失败");
		}
	}
}
